import axios from 'axios'

const service = axios.create({
  baseURL: 'http://192.168.10.126',
  timeout: 50000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (window.xAToken) {
      console.log('client token', window.xAToken)
      config.headers['X-AToken'] = window.xAToken
    }

    let ticket = window.sessionStorage.getItem('loginTicket')
    if (ticket) {
      config.headers['X-AToken'] = JSON.parse(ticket)['access_token']
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the status code is not 200, it is judged as an error.
    if (response.status !== 200) {
      return Promise.reject(res)
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    const { response } = error

    if (response) {
      return Promise.reject(response.data)
    } else {
      return Promise.reject(error)
    }
  }
)

export default service